package lagou.boot;

import com.lagou.entity.RpcRequest;
import com.lagou.service.IUserService;
import com.lagou.utils.getMap;
import lagou.client.RPCConsumer;
import lagou.handler.UserClientHandler;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ConsumerBoot {

    //参数定义
    private static final String PROVIDER_NAME = "UserService#sayHello#";

    private static Mapper mapper;

    private static Map<String ,Long> time = new TreeMap<String, Long>();

    static {
        try {
            mapper = new Mapper();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ConsumerBoot.start();
    }

    public static void start()throws Exception{
        CuratorFramework client = mapper.getClient();
        List<String> strings = client.getChildren().forPath("/");


        while (true){
            for (String string : strings) {
                System.out.println("当前服务端地址："+string);
                String path = new String(client.getData().forPath("/"+string));
                time.put(string,Long.valueOf(path));
            }
            String string = getMap.accordingToOrder(time);
            Long times = time.get(string);
            String[] split = string.split(":");
            mapper.initClient(split[0],Integer.parseInt(split[1]));
            Map<String, UserClientHandler> userClientHandlerMap = mapper.getUserClientHandlerMap();

            final Long[] zy = {0L};

            IUserService service = (IUserService) RPCConsumer.createProxy(IUserService.class,userClientHandlerMap.get(string));
            //2.循环给服务器写数据
            if (System.currentTimeMillis() - times > 5000){
                System.out.println("拒绝");
                continue;
            }else if( times > zy[0]){
                System.out.println("放行");
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName("com.lagou.entity.RpcRequest");
                rpcRequest.setMethodName("getRpcRequest");
                rpcRequest.setRequestId("userServiceImpl");
                rpcRequest.setParameters(new Object[]{"Hi"});
                rpcRequest.setParameterTypes(new Class[]{String.class});
                String result = service.getRpcRequest(rpcRequest);
                System.out.println(result+",服务器地址："+string);
                System.out.println();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
